<template>
<div>
  <mavon-editor
    class="me-editor"
    ref="md"
    v-model="editor.value"
    @imgAdd="imgAdd"
    v-bind="editor">
    <!-- 左工具栏后加入自定义按钮  -->
  <template slot="left-toolbar-after">
    <button
      type="button"
      @click="uploadVideo"
      class="el-icon-video-camera-solid"
      aria-hidden="true"
      title="上传视频"
    ></button>
  </template>
  </mavon-editor>
   <!-- 在这里放一个隐藏的input，用来选择文件 -->
    <input ref="uploadInput" style="display: none" type="file" @change="uploadVideoChange"/>
    </div>
</template>


<script>

  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import {upload} from '@/api/upload'

  export default {
    name: 'MarkdownEditor',
    props: {
      editor: Object
    },
    data() {
      return {}
    },
    mounted() {
      this.$set(this.editor, 'ref', this.$refs.md)
    },
    methods: {
      imgAdd(pos, $file) {
        let formdata = new FormData();
        formdata.append('image', $file);
        upload(formdata).then(data => {
          // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
          if (data.success) {
            this.$refs.md.$img2Url(pos, data.data);
          } else {
            this.$message({message: data.msg, type: 'error', showClose: true})
          }

        }).catch(err => {
          this.$message({message: err, type: 'error', showClose: true});
        })
      },
       uploadVideo() {
      // 通过ref找到隐藏的input标签，触发它的点击方法
      this.$refs.uploadInput.click()
    },
    // 监听input获取文件的状态
    uploadVideoChange(e) {
      // 获取到input选取的文件
      const file = e.target.files[0]
      // 创建form格式的数据，将文件放入form中，logo是与后台定义的字段
      const formdata = new FormData()
      formdata.append('image', file)
      upload(formdata).then(data => {
          if (data.success) {
            this.$refs.md.insertText(this.$refs.md.getTextareaDom(),
          {
            prefix: `<video id="video" controls="controls" preload="none" poster="封面">
      <source id="mp4" src="${data.data}" type="video/mp4">
</video>`,
            subfix: '',
            str: ''
          })
          } else {
            this.$message({message: data.msg, type: 'error', showClose: true})
          }

        }).catch(err => {
          this.$message({message: err, type: 'error', showClose: true});
        })
    }
    },
    components: {
      mavonEditor
    }
  }
</script>
<style scoped>

  .me-editor {
    z-index: 6 !important;
    min-height: 650px;
  }

  .v-note-wrapper.fullscreen {
    top: 60px !important
  }
</style>
